<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>集装箱业务报表</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div id="takeoutMain">
      <a-form layout="inline" :model="form" style="margin-top:0px;">
        <a-form-item label="时间">
          <select class="dateTypeSelect" v-model="dateType" @change="onChangeDateType">
            <option :value="0">请选择</option>
            <option :value="1">周报</option>
            <option :value="2">月报</option>
          </select>
          <a-range-picker style="width:220px" @change="timeChange" :value="timeValue" />
        </a-form-item>
        <a-form-item label="客户名称">
          <a-input v-model="form.custNameLike" />
        </a-form-item>
        <a-form-item label="所属部门">
          <a-tree-select
            class="selectInputWidth"
            v-model="form.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :load-data="onLoadData"
            :tree-data="deptTreeData"
            placeholder="请选择"
            @change="onChangeTree"
          ></a-tree-select>
        </a-form-item>
        <a-form-item label="所属销售">
          <a-select v-model="form.sellerId" class="selectInputWidth">
            <a-select-option value>全部</a-select-option>
            <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="订单类型">
          <a-select v-model="form.orderType" style="width:150px">
            <a-select-option value>全部</a-select-option>
            <a-select-option value="DOMESTIC_TRADE_EXPORTS">内贸出口订单</a-select-option>
            <a-select-option value="DOMESTIC_TRADE_IMPORTS">内贸进口订单</a-select-option>
            <a-select-option value="FOREIGN_TRADE_EXPORTS">外贸出口订单</a-select-option>
            <a-select-option value="FOREIGN_TRADE_IMPORTS">外贸进口订单</a-select-option>
            <a-select-option value="UNITED_TRANSPORT_EXPORTS">联运出口订单</a-select-option>
            <a-select-option value="UNITED_TRANSPORT_IMPORTS">联运进口订单</a-select-option>
            <a-select-option value="PURE_LAND_TRANSPORTS">纯陆运订单</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="check">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="excelExport">导出Excel</a-button>
        </a-form-item>
      </a-form>
      <a-card style="text-align:center; margin-top:24px;">
        <a-row :gutter="[16]">
          <a-col :span="5" class="assent">
            <div class="assent_mes">总箱量（个）</div>
            <div class="assent_shu">{{statisticsObj.containerNum}}</div>
          </a-col>
          <a-col :span="5" class="assent">
            <div class="assent_mes">总应收（元）</div>
            <div class="assent_shu">{{statisticsObj.receivableAmount}}</div>
          </a-col>
          <a-col :span="5" class="assent">
            <div class="assent_mes">总应付（元）</div>
            <div class="assent_shu">{{statisticsObj.payableAmount}}</div>
          </a-col>
          <a-col :span="5" class="assent">
            <div class="assent_mes">总毛利（元）</div>
            <div class="assent_shu">{{statisticsObj.profit}}</div>
          </a-col>
          <a-col :span="4">
            <div class="assent_mes">毛利率</div>
            <div class="assent_shu">{{statisticsObj.profitRateStr}}%</div>
          </a-col>
        </a-row>
      </a-card>
      <a-table
        :columns="columns"
        :loading="loading"
        :data-source="data"
        style="margin-top:25px;"
        :scroll="{x:2000}"
        :pagination="pagination"
        :row-key="(record,index) => index"
      ></a-table>
    </div>
  </div>
</template>
<script>
import { queryAllSellerDown, queryDeptDown } from '@/api'
import { queryJTBusinessReportList } from '@/api/dataBI'
import { commonExport } from '@/api/request'
import moment from 'moment'
import getWeek from '@/common/getDate'
const deptData = {
  type: 2, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL'
}
const sellerData = {
  type: 2, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL',
  status: 1
}
const columns = [
  {
    title: '序号',
    width: 80,
    customRender: (text, record, index) => {
      return index + 1
    }
  },
  {
    title: '订单类型',
    dataIndex: 'orderTypeName',
    customRender: (text, record, index) => {
      return record.orderTypeName || '--'
    }
  },
  {
    title: '所属部门',
    dataIndex: 'department',
    customRender: (text, record, index) => {
      return record.department || '--'
    }
  },
  {
    title: '所属销售',
    dataIndex: 'seller',
    customRender: (text, record, index) => {
      return record.seller || '--'
    }
  },
  {
    title: '客户名称',
    dataIndex: 'custName',
    customRender: (text, record, index) => {
      return record.custName || '--'
    }
  },
  {
    title: '时间',
    dataIndex: 'dateRange',
    customRender: (text, record, index) => {
      return record.dateRange || '--'
    }
  },
  {
    title: '箱量',
    dataIndex: 'containerNum',
    customRender: (text, record, index) => {
      return record.containerNum || '--'
    }
  },
  {
    title: '应收金额（元）',
    dataIndex: 'receivableAmount',
    customRender: (text, record, index) => {
      return record.receivableAmount.toFixed(2)
    }
  },
  {
    title: '应付金额（元）',
    dataIndex: 'payableAmount',
    customRender: (text, record, index) => {
      return record.payableAmount.toFixed(2)
    }
  },
  {
    title: '毛利（元）',
    dataIndex: 'profit',
    customRender: (text, record, index) => {
      return record.profit.toFixed(2)
    }
  },
  {
    title: '毛利率',
    dataIndex: 'profitRateStr',
    customRender: (text, record, index) => {
      return record.profitRateStr ? `${record.profitRateStr}%` : '--'
    }
  }
]
export default {
  data () {
    return {
      dateType: 1,
      deptTreeData: [],
      sellers: [],
      options: [],
      form: {
        orderType: '',
        custNameLike: '', // 客户名称
        deptId: '', // 部门id
        sellerId: '', // 销售id
        startQueryDate: '', // 开始日期
        endQueryDate: '' // 结束日期
      },
      pageNum: 1,
      pageSize: 10,
      loading: true,
      data: [],
      columns,
      pagination: {},
      btnControl: {},
      timeValue: [],
      statisticsObj: {}
    }
  },
  methods: {
    containerListRequest (e) {
      this.loading = true
      queryJTBusinessReportList(e).then(res => {
        this.data = res.data.reportlist.list
        this.statisticsObj = {
          containerNum: res.data.containerNum || 0,
          receivableAmount: res.data.receivableAmount ? res.data.receivableAmount.toFixed(2) : '0.00',
          payableAmount: res.data.payableAmount ? res.data.payableAmount.toFixed(2) : '0.00',
          profit: res.data.profit ? res.data.profit.toFixed(2) : '0.00',
          profitRateStr: res.data.profitRateStr
        }
        let currentPage = this.pageNum
        this.pagination = {
          current: currentPage,
          pageSize: res.data.reportlist.pageSize,
          total: res.data.reportlist.total,
          showQuickJumper: false,
          showSizeChanger: true,
          pageSizeOptions: ['10', '30', '50', '100', '500'],
          showTotal: total =>
            `共${total}条记录 第${currentPage}/${res.data.reportlist.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            let paramData = {
              ...this.form,
              pageSize: this.pageSize,
              pageNum: this.pageNum

            }
            this.containerListRequest(paramData)
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            let paramData = {
              pageSize: this.pageSize,
              pageNum: this.pageNum,
              ...this.form
            }
            this.containerListRequest(paramData)
          }
        }
        setTimeout(() => {
          this.loading = false
        }, 300)
      }).catch(() => {
        setTimeout(() => {
          this.loading = false
        }, 300)
      })
    },
    onChangeDateType () {
      let dateType = this.dateType
      if (dateType === 1) {
        let startQueryDate = getWeek.getStartDayOfWeek()
        let endQueryDate = getWeek.getEndDayOfWeek()
        this.form.startQueryDate = startQueryDate
        this.form.endQueryDate = endQueryDate
        this.timeValue = [moment(startQueryDate), moment(endQueryDate)]
      } else if (dateType === 2) {
        let startQueryDate = getWeek.getStartDayOfMonth()
        let endQueryDate = getWeek.getEndDayOfMonth()
        this.form.startQueryDate = startQueryDate
        this.form.endQueryDate = endQueryDate
        this.timeValue = [moment(startQueryDate), moment(endQueryDate)]
      }
    },
    timeChange (date, dateStr) {
      this.dateType = 0
      this.timeValue = date
      this.form.startQueryDate = dateStr[0]
      this.form.endQueryDate = dateStr[1]
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptDown({ parentId: treeNode.dataRef.key, ...deptData }).then(
          rsp => {
            let childrenData = []
            rsp.data.forEach(value => {
              childrenData.push({
                title: value.name,
                key: value.deptId,
                value: value.deptId
              })
            })
            treeNode.dataRef.children = childrenData
            this.deptTreeData = [...this.deptTreeData]
            resolve()
          }
        )
      })
    },
    initDept (e) {
      queryDeptDown(e).then(rsp => {
        let initData = []
        rsp.data.forEach((value, index) => {
          initData.push({
            title: value.name,
            key: value.deptId,
            value: value.deptId
          })
        })
        this.deptTreeData = initData
      })
    },
    onChangeTree (value) {
      this.initSellerDown(value)
    },
    initSellerDown (deptId) {
      queryAllSellerDown({ ...sellerData, deptId }).then(rsp => {
        this.sellers = rsp.data.map((v, i) => {
          if (!v.uiId) {
            v.name = '请选择'
            v.uiId = ''
          }
          return v
        })
      })
    },
    check () {
      this.pageNum = 1
      this.containerListRequest({
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    },
    excelExport () {
      commonExport('/truckReport/exportJTBusinessReportList', {
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: this.columns
      })
    }
  },
  mounted () {
    this.initDept(deptData) // 所属部门
    this.initSellerDown() // 所属销售
    let startQueryDate = getWeek.getStartDayOfWeek()
    let endQueryDate = getWeek.getEndDayOfWeek()
    this.form.startQueryDate = startQueryDate
    this.form.endQueryDate = endQueryDate
    this.timeValue = [moment(startQueryDate), moment(endQueryDate)]
    setTimeout(() => {
      this.check()
    }, 1)
    this.$nextTick(() => {
      this.btnControl = this.$root._bc
    })
  }
}
</script>

<style lang="less" scoped>
#takeoutMain {
  padding: 24px;
  margin: 24px;
  background: #fff;
  min-height: 700px;

  .dateTypeSelect {
    outline: none;
    border: 1px solid #e2e2e2;
    border-radius: 4px;
    height: 32px;
    line-height: 32px;
    padding: 0 2px;
    margin-right: 5px;
  }
}
</style>
